import {CALL_API, isRSAA} from 'redux-api-middleware'
import {isUndefined} from '../util'
import MYT_AUTH from '../oauth2/MYT_AUTH'
import rely from '../oauth2/oauth2rely'
import {modalTip} from '../components/ModalTip'

const error = (err) => {
    modalTip.error(err);
};

const nextActionWidthAuthorization = (action, next, accessToken) => {
    let authHeader = `Bearer ${accessToken}`;
    // 插入头身份信息
    if (isUndefined(action[CALL_API].headers)) {
        action[CALL_API].headers = {
            'Authorization': authHeader
        }
    } else {
        action[CALL_API].headers['Authorization'] = authHeader;
    }
    // 移除 MYT_AUTH 标记
    delete action[CALL_API][MYT_AUTH];
    next(action);
};

export default store => next => action => {
    /**
     * redux-api-middleware 前处理，加入access的认证头
     * 若 access token 过期，则使用refresh token 刷新，若仍然无法刷新，则提示重新登录
     */
    if (!isRSAA(action)) {
        return next(action);
    }

    // 检查是否有 MYT_AUTH，并且为 true
    const callAPI = action[CALL_API];
    if ((!callAPI.hasOwnProperty(MYT_AUTH)) || (!callAPI[MYT_AUTH])) {
        return next(action);
    }

    // 获取 store 中的tokens
    let tokens = rely.getTokens();
    // 检查 accessToken是否过期
    if (rely.isTokenValid(tokens)) {
        nextActionWidthAuthorization(action, next, tokens.access_token);
    } else {
        // 刷新token
        rely.prepareRefresh(
            () => {
                rely.refresh((newAccessToken) => {
                    nextActionWidthAuthorization(action, next, newAccessToken);
                }, error)
            },
            () => {
                let newTokens = rely.getTokens();
                nextActionWidthAuthorization(action, next, newTokens.access_token);
            });

    }
};
